#encoding:utf8 

import os
import sys
import platform


PATH_PROJ = os.path.abspath(__file__ + "/../../")       #git 根路径 
DIR_FRAME = "ding-framework"
DIR_CONF = "conf"
NGINX_CONF = PATH_PROJ + "/conf/%s.conf"
WIN_DEV = "D:\\Program\\openresty-1.21.4.1-win64\\nginx.exe"


def pre_files():
    fils = [
        "conf/logs/logic/access.log",
        "conf/logs/logic/error.log",
        "conf/logs/nginx/access.log",
        "conf/logs/nginx/error.log",
    ]
    for v in fils:
        f = os.path.join(PATH_PROJ, v)
        if not os.path.isfile(f):
            p_dir = os.path.dirname(f)
            if not os.path.isdir(p_dir):
                os.makedirs(p_dir)
            with open(f, "w+") as fp:
                pass


def pack_framework():
    path_script = os.path.join(PATH_PROJ, "libs", DIR_FRAME)
    rel_p = os.path.abspath(path_script)
    os.chdir(rel_p)
    print("--------")
    os.system("lua ./squish ")
    print("--------")


def run_openresty(ngxconf, isdaemon):
    os.chdir(PATH_PROJ)
    ext = ''' -g "daemon off;"''' if isdaemon else ""
    ngxconf = NGINX_CONF.format(conf=ngxconf)

    binary = WIN_DEV if platform.system() == "Windows" else "openresty"
    cmd_str = "{binary} -p {cur} -c {conf} {ext}".format(
        binary = binary, conf=ngxconf, ext=ext, cur=os.path.join(PATH_PROJ, DIR_CONF))
    ret = os.system(cmd_str)
    if (ret == 0):
        print("Openresty run suc!")


def execute(ngxconf, isdaemon=False):
    pre_files()
    pack_framework()
    run_openresty(ngxconf, isdaemon)


if __name__ == "__main__":
    if len(sys.argv) <= 1:
        print("input the config filename in /conf/logic/*.conf")
        sys.exit()
    ngxconf = sys.argv[1]
    execute(ngxconf)
